//
//  RequirementDetail.m
//  APJ HRadar
//
//  Created by Andy liu on 14-3-29.
//  Copyright (c) 2014年 APJ. All rights reserved.
//

#import "RequirementDetail.h"
#import "ResourceRequirement.h"
#import "HRStore.h"
#import "RequirementCell.h"
#import "JobhunterCell.h"
#import "Interview.h"
#import "Staff.h"
#import "InterviewCell.h"
#import "StaffProfileViewController.h"
#import "Dept.h"

@interface RequirementDetail ()
{
    NSArray *array;
    NSMutableArray *interview;
    NSMutableDictionary *interviewer;
    NSMutableArray *_staff;
    NSArray *outarray;
    NSMutableArray *toalarray;
}
@end

@implementation RequirementDetail
@synthesize requirememt,staff,_currentMonth,reqId,byType,skillName;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self buildSReqDictionary];
}

//- (NSComparisonResult)compare:(id)ResourceRequirement {
//    return [ compare:ResourceRequirement];
//}

- (void)buildSReqDictionary
{
    if (!_currentMonth) {
        _currentMonth = [NSDate date];
    }
    if (byType==1) {
        array = [[HRStore sharedStore] reqBySkill:skillName inMonth:[_currentMonth timeIntervalSince1970]];
    }
    else
    {
        array = [[HRStore sharedStore] reqByDept:reqId inMonth:[_currentMonth timeIntervalSince1970]];
    }
    toalarray=[[NSMutableArray alloc] init];
    
    if (byType==1) {
        outarray = [[HRStore sharedStore] reqBySkillAndOutstanding:skillName inMonth:[_currentMonth timeIntervalSince1970]];
        for (ResourceRequirement *req in outarray) {
            NSArray *cinser=[[HRStore sharedStore] confirmedInterviewForReq:req.reqId];
            if ([req count]>[cinser count]) {
                //req.count=req.count-cinser.count;
                [toalarray addObject:req];
            }
        }
    }
    else
    {
        outarray = [[HRStore sharedStore] reqBydeptAndOutstanding:reqId inMonth:[_currentMonth timeIntervalSince1970]];
        for (ResourceRequirement *req in outarray) {
            NSArray *cinser=[[HRStore sharedStore] confirmedInterviewForReq:req.reqId];
            if ([req count]>[cinser count]) {
                //req.count=req.count-cinser.count;
                [toalarray addObject:req];
            }
        }
    }
    [toalarray addObjectsFromArray:array];
    NSSortDescriptor *sortDescriptor;
    sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"reqArriveDate" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
 
    array = [toalarray sortedArrayUsingDescriptors:sortDescriptors];
    
    interview=[[NSMutableArray alloc] init];

    for (int i=0; i<array.count;i++) {
        ResourceRequirement *res=[array objectAtIndex:i];
        NSArray *inv=[[HRStore sharedStore] interviewOfReqId:res.reqId];
        for (int i=0; i<inv.count;i++) {
            Interview *inskill=[inv objectAtIndex:i];
            [interview addObject:inskill];
        }
    }
    interviewer=[[NSMutableDictionary alloc] init];
    _staff=[[NSMutableArray alloc] init];
    for (int i=0; i<interview.count;i++) {
        Interview *inskill=[interview objectAtIndex:i];
        NSMutableArray *arr=[[NSMutableArray alloc] init];
        NSString *_staffId=[[NSString alloc] initWithFormat:@"%d",inskill.staffId];
        Staff *staskil=[[HRStore sharedStore] findStaffById:inskill.staffId];
        ResourceRequirement *res=[[HRStore sharedStore] ResourceRequirementByReqId:inskill.reqId];
        staskil.englishName=res.reqNo;
        if ([interviewer objectForKey:_staffId]) {
            arr=[interviewer objectForKey:_staffId];
            [arr addObject:inskill];
        }
        else
        {
            [arr addObject:inskill];
            [interviewer setObject:arr forKey:_staffId];
            staskil.techType=inskill.techType;
            staskil.jobTitle=inskill.position;
            [_staff addObject:staskil];
        }
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView==self.staff) {
        return _staff.count;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger ret=0;
    if(tableView == self.requirememt)
        ret= array.count;
    else if(tableView == self.staff)
    {
        Staff *st=[_staff objectAtIndex:section];
         NSString *_staffId=[[NSString alloc] initWithFormat:@"%d",st.staffId];
        NSArray *arry =[interviewer objectForKey:_staffId];
        ret= arry.count;
    }
    return ret;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
     if (tableView==self.staff) {
         Staff *st=[_staff objectAtIndex:section];
         NSString *str=[NSString stringWithFormat:@"%@\t\t%@\t\t%@\t\t%@",st.chineseName,st.techType,st.jobTitle,st.englishName];
         return str;
     }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView==self.staff) {
        return 40.f;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RequirementCell *cell;
    if(tableView == self.requirememt)
    {
        requirememt=tableView;
        
        [tableView registerNib:[UINib nibWithNibName:@"RequirementCell" bundle:nil] forCellReuseIdentifier:@"RequirementCell"];
    
        cell= [tableView dequeueReusableCellWithIdentifier:@"RequirementCell"];
    
        if (cell == nil) {
            cell = [[RequirementCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RequirementCell"];
        }
        ResourceRequirement *resour=[array objectAtIndex:indexPath.row];
        cell.reqNo.text=resour.reqNo;
        cell.post.text=resour.position;
        cell.commentText.text=resour.comments;
        cell.skill.text=resour.techType;
        Dept *_dept=[[HRStore sharedStore] findDeptById:resour.deptId];
        cell.dept.text=_dept.deptShortName;
        NSDate *time = [NSDate dateWithTimeIntervalSince1970:resour.reqArriveDate];
        NSDateFormatter *formate = [[NSDateFormatter alloc] init];
        formate.dateFormat = @"dd-MMM-YYYY";
        cell.dateTime.text = [NSString stringWithFormat:@"%@", [formate stringFromDate:time]];
        
        NSDateFormatter *formate1 = [[NSDateFormatter alloc] init];
        formate1.dateFormat = @"MM-YYYY";

        
        NSString *data1=[formate1 stringFromDate:time];
        NSString *data2=[formate1 stringFromDate:_currentMonth];
        NSComparisonResult result = [data1 compare:data2];

        if (result<0) {
           cell.dateTime.textColor=[UIColor redColor];
           NSArray *cinser=[[HRStore sharedStore] confirmedInterviewForReq:resour.reqId];
            if(resour.count>1)
            {
            cell.count.text=[NSString stringWithFormat:@"%d (%d/%d)",resour.count-cinser.count,resour.count-cinser.count,resour.count];
            }
            else{
                cell.count.text=[NSString stringWithFormat:@"%d",resour.count];
            }
        }
        else{
             cell.count.text=[NSString stringWithFormat:@"%d",resour.count];
        }
        
        int counts=0;
        for (int i=0; i<interview.count;i++) {
            Interview *inskill=[interview objectAtIndex:i];
            if (inskill.reqId==resour.reqId && [inskill.interviewStatus isEqualToString:@"Confirm"]) {
                counts+=1;
            }
        }
        if (counts>=resour.count && result==0) {
            cell.image.hidden=NO;
        }
        else
        {
            cell.image.hidden=YES;
            
        }
    }
    else if(tableView == self.staff)
    {
        staff = tableView;
        [tableView registerNib:[UINib nibWithNibName:@"InterviewCell" bundle:nil] forCellReuseIdentifier:@"InterviewCell"];
        
        InterviewCell *cell= [tableView dequeueReusableCellWithIdentifier:@"InterviewCell"];
        
        if (cell == nil) {
            cell = [[InterviewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"InterviewCell"];
        }
        Staff *st=[_staff objectAtIndex:indexPath.section];
        NSString *_staffId=[[NSString alloc] initWithFormat:@"%d",st.staffId];
        NSArray *arry =[interviewer objectForKey:_staffId];
        Interview *inskill=[arry objectAtIndex:indexPath.row];
        cell.description.text=inskill.comments; //@"对.NET还算比较了解";
        cell.result.text=inskill.interviewStatus;//@"待定";
        
        if ([inskill.interviewStatus isEqualToString:@"Confirm"]) {
            cell.image.hidden=NO;
        }
        else
        {
            cell.image.hidden=YES;
        }
        //cell.datetime.text=@"2014-04-01";
        NSDate *time = [NSDate dateWithTimeIntervalSince1970:inskill.interviewTime];
        NSDateFormatter *formate = [[NSDateFormatter alloc] init];
        formate.dateFormat = @"dd-MMM-YYYY";
        cell.datetime.text = [NSString stringWithFormat:@"%@", [formate stringFromDate:time]];
        cell.interviewer.text=inskill.interviewer;//@"richard";
        return cell;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 130.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == self.staff)
    {
        StaffProfileViewController *staffPro = [[StaffProfileViewController alloc] init];
        Staff *st=[_staff objectAtIndex:indexPath.section];
        [staffPro setStaff:st];
        [[staffPro navigationItem] setTitle:@"Staff Detail Info."];
        [[self navigationController] pushViewController:staffPro animated:YES];
    }
}

@end
